package com.tavio.vaultboy.collision;

import org.andengine.entity.primitive.Line;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.tavio.vaultboy.element.Element;

public class BoundingBox {
	public Vertex[] vertexes = new Vertex[4];
	
	public Rectangle[] debugRects = new Rectangle[4];
	
	private Element element;
	
	private boolean isDebug;
	
	public float top;
	
	public float bottom;
	
	public float left;
	
	public float right;

	public BoundingBox(Element element, boolean debug, VertexBufferObjectManager vertexBufferObjectManager, Scene scene) {
		this.element = element;
		this.isDebug = debug;
		
		top = element.y;
		bottom = element.y + element.height;
		left = element.x;
		right = element.x + element.width;
		
		vertexes[0] = new Vertex(element.x, element.y);
		vertexes[1] = new Vertex(element.x + element.width, element.y);
		vertexes[2] = new Vertex(element.x + element.width, element.y + element.height);
		vertexes[3] = new Vertex(element.x, element.y + element.height);
		
		if(debug) {
			debugRects[0] = new Rectangle(vertexes[0].x, vertexes[0].y, 2, element.height, vertexBufferObjectManager);
			debugRects[1] = new Rectangle(vertexes[0].x, vertexes[0].y, element.width, 2, vertexBufferObjectManager);
			debugRects[2] = new Rectangle(vertexes[1].x, vertexes[1].y, 2, element.height, vertexBufferObjectManager);
			debugRects[3] = new Rectangle(vertexes[3].x, vertexes[3].y, element.width, 2, vertexBufferObjectManager);
			
			for(Rectangle r : debugRects) {
				r.setZIndex(1);
				scene.attachChild(r);
			}
			
		}
	}
	
	public void update() {
		
		vertexes[0].setPosition(element.x, element.y);
		vertexes[1].setPosition(element.x + element.width, element.y);
		vertexes[2].setPosition(element.x + element.width, element.y + element.height);
		vertexes[3].setPosition(element.x, element.y + element.height);
		
		top = element.y;
		bottom = element.y + element.height;
		left = element.x;
		right = element.x + element.width;
		
		if(isDebug) {
			debugRects[0].setPosition(vertexes[0].x, vertexes[0].y);
			debugRects[1].setPosition(vertexes[0].x, vertexes[0].y);
			debugRects[2].setPosition(vertexes[1].x, vertexes[1].y);
			debugRects[3].setPosition(vertexes[3].x, vertexes[3].y);
		}
	}
	
	public boolean collidesWith (BoundingBox boundingBox) {
		if (this.bottom <= boundingBox.top) return false;
        if (this.top >= boundingBox.bottom) return false;
        if (this.right <= boundingBox.left) return false;
        if (this.left >= boundingBox.right) return false;
		
		return true;
	}
	
}
